import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { Image } from "antd";
import styles from "./ProductManageQuery.module.css";
import AddProductManage from "./AddProductManage";
import EditProductManage from "./EditProductManage";

interface ProductResponse {
    code: number;
    message: string;
    data: {
        totalCount: number;
        totalPage: number;
        pageData: Array<{
            id: number;
            img: string;
            team: string;
            typeof: string;
            productName: string;
            sku: string;
        }>;
    };
}

interface SearchParams {
    team: string;
    typeof: string;
    productName: string;
    sku: string;
    pageIndex: number;
    pageSize: number;
}

const ProductManageQuery = () => {
    //定义数组对象
    const [productList, setProductList] = useState<ProductResponse['data']['pageData']>([]);
    const [totalCount, setTotalCount] = useState(0);

    // 搜索条件状态
    const [searchParams, setSearchParams] = useState<SearchParams>({
        team: '',
        typeof: '',
        productName: '',
        sku: '',
        pageIndex: 1,
        pageSize: 10
    });

    // 控制弹窗显示
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const [isEditModalVisible, setIsEditModalVisible] = useState(false);
    const [editingProduct, setEditingProduct] = useState<ProductResponse['data']['pageData'][0] | null>(null);

    //定义导航
    const navigate = useNavigate();

    // 处理搜索条件变化
    const handleSearchChange = (e: React.ChangeEvent<HTMLInputElement>) => {
        const { name, value } = e.target;
        setSearchParams(prev => ({
            ...prev,
            [name]: value
        }));
    };

    // 处理分页变化
    const handlePageChange = (pageIndex: number) => {
        setSearchParams(prev => ({
            ...prev,
            pageIndex
        }));
    };

    // 处理每页条数变化
    const handlePageSizeChange = (pageSize: number) => {
        setSearchParams(prev => ({
            ...prev,
            pageSize,
            pageIndex: 1 // 切换每页条数时重置为第一页
        }));
    };

    // 获取产品列表数据
    const fetchProductList = async () => {
        try {
            // 处理查询参数
            const queryParamsObj = {
                Team: searchParams.team || null,
                Typeof: searchParams.typeof || null,
                ProductName: searchParams.productName || null,
                SKU: searchParams.sku || null,
            };
            
            // 过滤掉null值的查询参数
            const filteredParams = Object.fromEntries(
                Object.entries(queryParamsObj).filter(([_, value]) => value !== null)
            );

            // 构建最终的参数对象，确保分页参数一定存在
            const finalParams = {
                ...filteredParams,
                PageIndex: searchParams.pageIndex.toString(),
                PagePage: searchParams.pageSize.toString()  // 修改为PagePage
            };

            const queryString = new URLSearchParams(finalParams).toString();
            const response = await fetch(`http://localhost:5233/api/ProductManage/ProductManageQuery?${queryString}`);
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            const result: ProductResponse = await response.json();
            if (result.code === 200 && result.data) {
                setProductList(result.data.pageData);
                setTotalCount(result.data.totalCount);
            } else {
                setProductList([]);
                setTotalCount(0);
            }
        } catch (error) {
            setProductList([]);
            setTotalCount(0);
        }
    };

    // 组件加载时获取数据
    useEffect(() => {
        fetchProductList();
    }, [searchParams.pageIndex, searchParams.pageSize]); // 当页码或每页条数变化时重新获取数据

    // 处理搜索按钮点击
    const handleSearch = (e: React.FormEvent) => {
        e.preventDefault();
        setSearchParams(prev => ({
            ...prev,
            pageIndex: 1 // 搜索时重置为第一页
        }));
        fetchProductList();
    };

    // 重置搜索条件
    const handleReset = () => {
        setSearchParams({
            team: '',
            typeof: '',
            productName: '',
            sku: '',
            pageIndex: 1,
            pageSize: 10
        });
    };

    // 添加成功后刷新列表
    const handleAddSuccess = () => {
        setIsAddModalVisible(false);
        fetchProductList();
    };

    // 构建完整的图片URL
    const getImageUrl = (imgPath: string) => {
        if (!imgPath) return '';
        
        // 确保使用正确的URL格式：http://localhost:5233/img/ProductManage/文件名
        // 从上传测试我们知道这个格式是正确的
        if (imgPath.startsWith('http://localhost:5233/img/ProductManage/')) {
            return imgPath;
        }
        
        // 如果是其他格式，提取文件名并构建正确的URL
        const fileName = imgPath.split('/').pop();
        if (!fileName) {
            return '';
        }
        
        const correctUrl = `http://localhost:5233/img/ProductManage/${fileName}`;
        return correctUrl;
    };

    // 图片加载错误处理
    const handleImageError = (e: any) => {
        const img = e.target;
        const currentSrc = img.src;
        
        // 尝试不同的URL格式
        if (!img.hasTriedFallback) {
            img.hasTriedFallback = true;
            
            // 如果原URL包含完整路径，尝试只使用文件名
            if (currentSrc.includes('/')) {
                const fileName = currentSrc.split('/').pop();
                const fallbackUrl1 = `http://localhost:5233/img/ProductManage/${fileName}`;
                img.src = fallbackUrl1;
                return;
            }
        }
        
        if (!img.hasTriedFallback2) {
            img.hasTriedFallback2 = true;
            const fileName = currentSrc.split('/').pop();
            const fallbackUrl2 = `http://localhost:5233/wwwroot/img/ProductManage/${fileName}`;
            img.src = fallbackUrl2;
            return;
        }
        
        // 所有备用方案都失败，显示错误信息
        img.style.display = 'none';
        const parent = img.parentElement;
        if (parent) {
            parent.innerHTML = '<div style="padding: 20px; text-align: center; color: #999; border: 1px dashed #ddd;">图片无法加载</div>';
        }
    };

    // 处理编辑按钮点击
    const handleEdit = (product: ProductResponse['data']['pageData'][0]) => {
        setEditingProduct(product);
        setIsEditModalVisible(true);
    };

    // 编辑成功后的处理
    const handleEditSuccess = () => {
        setIsEditModalVisible(false);
        setEditingProduct(null);
        fetchProductList();  // 刷新列表
    };

    // 处理删除
    const handleDelete = async (id: number) => {
        if (!window.confirm('确定要删除这条产品记录吗？')) {
            return;
        }

        try {
            const response = await fetch(`http://localhost:5233/api/ProductManage/DelProductManage?Id=${id}`, {
                method: 'DELETE',
            });

            const result = await response.json();
            
            if (result.code === 200) {
                alert('删除成功');
                fetchProductList(); // 刷新列表
            } else {
                throw new Error(result.message || '删除失败');
            }
        } catch (error) {
            alert('删除失败，请重试');
        }
    };

    return (
        <div className={styles.container}>
            <div className={styles.header}>
                <h3 className={styles.title}>产品管理查询</h3>
                <button 
                    onClick={() => setIsAddModalVisible(true)} 
                    className={`${styles.operationButton} ${styles.addButton}`}
                >
                    添加产品
                </button>
            </div>

            {/* 搜索表单 */}
            <form onSubmit={handleSearch} className={styles.searchForm}>
                <div className={styles.searchRow}>
                    <div className={styles.searchItem}>
                        <label>产品团队：</label>
                        <input
                            type="text"
                            name="team"
                            value={searchParams.team}
                            onChange={handleSearchChange}
                            placeholder="请输入产品团队"
                        />
                    </div>
                    <div className={styles.searchItem}>
                        <label>产品类型：</label>
                        <input
                            type="text"
                            name="typeof"
                            value={searchParams.typeof}
                            onChange={handleSearchChange}
                            placeholder="请输入产品类型"
                        />
                    </div>
                    <div className={styles.searchItem}>
                        <label>产品名称：</label>
                        <input
                            type="text"
                            name="productName"
                            value={searchParams.productName}
                            onChange={handleSearchChange}
                            placeholder="请输入产品名称"
                        />
                    </div>
                    <div className={styles.searchItem}>
                        <label>产品SKU：</label>
                        <input
                            type="text"
                            name="sku"
                            value={searchParams.sku}
                            onChange={handleSearchChange}
                            placeholder="请输入产品SKU"
                        />
                    </div>
                    <div className={styles.searchButtons}>
                        <button type="submit" className={styles.searchButton}>查询</button>
                        <button type="button" onClick={handleReset} className={styles.resetButton}>重置</button>
                    </div>
                </div>
            </form>

            <table className={styles.table}>
                <thead>
                    <tr>
                        <th>产品ID</th>
                        <th>产品图片</th>
                        <th>产品团队</th>
                        <th>产品类型</th>
                        <th>产品名称</th>
                        <th>产品SKU</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {productList && productList.length > 0 ? (
                        productList.map((product) => (
                            <tr key={product.id}>
                                <td>{product.id}</td>
                                <td className={styles.imageCell}>
                                    {product.img ? (
                                    <div className={styles.imageWrapper}>
                                        <Image
                                            src={getImageUrl(product.img)}
                                            alt={`产品${product.productName}的图片`}
                                            width={120}
                                            height={120}
                                            preview={false}
                                            onError={handleImageError}
                                        />
                                    </div>
                                    ) : (
                                        <div className={styles.noImage}>暂无图片</div>
                                    )}
                                </td>
                                <td>{product.team}</td>
                                <td>{product.typeof}</td>
                                <td>{product.productName}</td>
                                <td>{product.sku}</td>
                                <td className={styles.operationCell}>
                                    <button 
                                        className={`${styles.operationButton} ${styles.editButton}`}
                                        onClick={() => handleEdit(product)}
                                    >
                                        编辑
                                    </button>
                                    <button 
                                        className={`${styles.operationButton} ${styles.deleteButton}`}
                                        onClick={() => handleDelete(product.id)}
                                    >
                                        删除
                                    </button>
                                </td>
                            </tr>
                        ))
                    ) : (
                        <tr>
                            <td colSpan={7} style={{ textAlign: 'center' }}>暂无数据</td>
                        </tr>
                    )}
                </tbody> 
            </table>

            {/* 分页控件 */}
            <div className={styles.pagination}>
                <span>共 {totalCount} 条</span>
                <select 
                    value={searchParams.pageSize} 
                    onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                    className={styles.pageSizeSelect}
                >
                    <option value="10">10条/页</option>
                    <option value="20">20条/页</option>
                    <option value="50">50条/页</option>
                    <option value="100">100条/页</option>
                </select>
                <button 
                    onClick={() => handlePageChange(searchParams.pageIndex - 1)}
                    disabled={searchParams.pageIndex === 1}
                    className={styles.pageButton}
                >
                    上一页
                </button>
                <span>第 {searchParams.pageIndex} 页</span>
                <button 
                    onClick={() => handlePageChange(searchParams.pageIndex + 1)}
                    disabled={searchParams.pageIndex * searchParams.pageSize >= totalCount}
                    className={styles.pageButton}
                >
                    下一页
                </button>
            </div>

            {/* 添加产品弹窗 */}
            {isAddModalVisible && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modalContent}>
                        <AddProductManage 
                            onClose={() => setIsAddModalVisible(false)}
                            onSuccess={handleAddSuccess}
                        />
                    </div>
                </div>
            )}

            {/* 编辑产品弹窗 */}
            {isEditModalVisible && editingProduct && (
                <div className={styles.modalOverlay}>
                    <div className={styles.modalContent}>
                        <EditProductManage 
                            productData={editingProduct}
                            onClose={() => {
                                setIsEditModalVisible(false);
                                setEditingProduct(null);
                            }}
                            onSuccess={handleEditSuccess}
                        />
                    </div>
                </div>
            )}
        </div>
    );
};

export default ProductManageQuery;